<?php

namespace App\Models\Train\TrainSeatInfo\Repositories;

use App\Models\Train\TrainSeatInfo\TrainSeatInfo;
use App\Trip\Repository\BaseRepository;
use Exception;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;

class TrainSeatInfoRepository extends BaseRepository implements Interfaces\TrainSeatInfoRepositoryInterface
{
    public function __construct(TrainSeatInfo $model)
    {
        parent::__construct($model);
    }

    /**
     * @throws Exception
     */
    public function addTrainSeatInfo(array $data): TrainSeatInfo
    {

        $validator = Validator::make($data, [
            'train_code' => "required",
            'from_code'  => "required",
            'to_code'    => "required",
            'seat_name'  => "required",
            'name'       => "required",
            'price'      => "required",
        ]);

        if ($validator->fails()) {
            throw new Exception("param error");
        }

        if ($seatInfo = $this->findByTrainCodeAndName($data['train_code'], $data['from_code'], $data['to_code'], $data['seat_name'], $data['name'])) {
            //如果价格变化
            $this->update($data, $seatInfo);
            return $seatInfo;
        }
        return $this->create($data);
    }


    public function findByTrainCodeAndName(string $train_code, string $from_code, string $to_code, string $seat_name,
                                           string $name): ?TrainSeatInfo
    {
        $cache_key = "Train:SeatInfo:{$train_code}:{$from_code}:{$to_code}:{$seat_name}:{$name}";
        if (Cache::has($cache_key)) {
            return Cache::get($cache_key);
        }
        $seatInfo = $this->findOneBy([
            'train_code' => $train_code,
            'from_code'  => $from_code,
            'to_code'    => $to_code,
            'name'       => $name,
            'seat_name'  => $seat_name,
        ]);

        $seatInfo && Cache::put($cache_key, $seatInfo, 30 * config('trip.ttl.day'));
        return $seatInfo;

    }

    public function listByTrainCodeAndSeatName(string $train_code, string $from_code, string $to_code, string $seat_name): Collection
    {
        return $this->findBy([
            'train_code' => $train_code,
            'from_code'  => $from_code,
            'to_code'    => $to_code,
            'seat_name'  => $seat_name,
        ]);
    }
}